import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/add_book")
public class AddBook extends HttpServlet {
    private static final String DB_URL = "jdbc:mysql://localhost:3306/linux_exam";
    private static final String DB_USER = "root";
    private static final String DB_PASSWORD = "1qaz@WSX#EDC";

    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        resp.setHeader("Access-Control-Allow-Origin","*");
        resp.setHeader("Access-Control-Allow-Methods","*");
        resp.setHeader("Access-Control-Allow-Headers","*");

        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        PrintWriter out = resp.getWriter();

        String number = req.getParameter("number");
        String name = req.getParameter("name");
        String author = req.getParameter("author");

        try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
             PreparedStatement stmt = conn.prepareStatement(
                     "INSERT INTO t_book (number, name, author) VALUES (?, ?, ?)")) {

            stmt.setString(1, number);
            stmt.setString(2, name);
            stmt.setString(3, author);

            int rows = stmt.executeUpdate();
            out.printf("{\"status\":\"%s\",\"message\":\"%s\"}",
                    rows > 0 ? "success" : "error",
                    rows > 0 ? "Book added" : "Add failed");
        } catch (SQLException e) {
            out.printf("{\"status\":\"error\",\"message\":\"%s\"}", e.getMessage());
        }
        out.close();
    }
}